<template>
  <div v-loading="queueLoading" class="merak-container-has-aside" curPageName="goods_allocation">
    <div class="merak-aside">
      <div class="title">{{ $t(`goods_attribute.${props.type}`) }}</div>
      <el-input
        v-model="treeState.filter"
        :placeholder="$t('merak.placeholder_filter')"
        :suffix-icon="Search"
        @input="value => treeRef?.filter(value)"
      />
      <div class="tree-wrapper">
        <el-scrollbar>
          <el-tree
            ref="treeRef"
            node-key="id"
            :data="treeState.data"
            :props="{ children: 'childs' }"
            :default-expanded-keys="expandedKeys"
            :filter-node-method="(value, tree) => tree.label.includes(value)"
            @current-change="handleCurrentChange"
          />
        </el-scrollbar>
      </div>
    </div>
    <div v-waterMarker class="merak-card">
      <el-tabs v-model="activeName">
        <el-tab-pane
          :label="$t('goods_attribute.property_sale')"
          :name="TabType.sales"
          :lazy="lazy[TabType.sales]"
          :style="{ left: activeName === TabType.sales ? '0' : '-100%' , zIndex: activeName === TabType.sales ? '0' : '-1'}"
        >
          <Sales
            ref="saleRef"
            :type="props.type"
            :queueId="queueId"
            :treeSelected="treeState.value"
            :lazy="lazy[TabType.sales]"
            @add="propId => handleAdd(TabType.sales, propId)"
          />
        </el-tab-pane>
        <el-tab-pane
          :label="$t('goods_attribute.property_clearance')"
          :name="TabType.clearance"
          :lazy="lazy[TabType.clearance]"
          :style="{ left: activeName === TabType.clearance ? '0' : '100%', zIndex: activeName === TabType.clearance ? '0' : '-1' }"
        >
          <Clearance
            ref="clearanceRef"
            :type="props.type"
            :queueId="queueId"
            :treeSelected="treeState.value"
            :lazy="lazy[TabType.clearance]"
            @add="propId => handleAdd(TabType.clearance, propId)"
          />
        </el-tab-pane>
      </el-tabs>
    </div>
    <Transition name="fade" mode="out-in">
      <AddQifa
        v-if="visible[TabType.sales]"
        :type="props.type"
        :typeId="treeState.value"
        :propId="propId"
        @close="refresh => handleClose(TabType.sales, refresh)"
      />
    </Transition>
    <Transition name="fade" mode="out-in">
      <AddClearance
        v-if="visible[TabType.clearance]"
        :type="props.type"
        :typeId="treeState.value"
        :propId="propId"
        @close="refresh => handleClose(TabType.clearance, refresh)"
      />
    </Transition>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted,getCurrentInstance } from "vue";

import { useRoute } from "vue-router";

import { ElInput, ElScrollbar, ElTree, ElTabs, ElTabPane } from "element-plus";

import { Search } from "@element-plus/icons-vue";

import Sales from "./Sales.vue";
import Clearance from "./Clearance.vue";

import AddQifa from "./AddQifa.vue";
import AddClearance from "./AddClearance.vue";

import useLoading from "@/hooks/useLoading";

import { ResultEnum } from "@/enums/httpEnum";
import { RouteType, TabType, TreeType, getDailyNecessitiesTree } from "@/api/modules/goodsArchive/allocation";
import { zIndex } from "html2canvas/dist/types/css/property-descriptors/z-index";

const props = defineProps<{
  type: RouteType;
}>();
const { proxy } = getCurrentInstance();
const route = useRoute();

const { queueLoading, queueId } = useLoading();

const treeRef = ref<InstanceType<typeof ElTree>>();

const saleRef = ref<InstanceType<typeof Sales>>();

const clearanceRef = ref<InstanceType<typeof Clearance>>();

const activeName = ref<TabType>(TabType.sales);

const propId = ref<string | number>();

const lazy = reactive({
  [TabType.sales]: activeName.value !== TabType.sales,
  [TabType.clearance]: activeName.value !== TabType.clearance
});

const visible = reactive({
  [TabType.sales]: false,
  [TabType.clearance]: false
});

const treeState = reactive<{
  data: TreeType[];
  value?: string;
  filter?: any;
}>({ data: [] });

const expandedKeys = computed(() => {
  const arr: string[] = [];
  if (!!route.query.key) {
    const routeKeys = route.query.key.toString().split("-");
    arr.push(routeKeys[0]);
  }
  return arr;
});

// 树点击
const handleCurrentChange: InstanceType<typeof ElTree>["onCurrent-change"] = (data, treeNode) => {
  if (!treeNode.isLeaf) return;
  const url = new URL(location.href);
  if (data.id === "all") {
    url.searchParams.delete("key");
  } else {
    url.searchParams.set("key", data.id.toString());
  }
  treeState.value = data.value.toString();
  // 还原默认标签
  activeName.value = TabType.sales;
  // 记录浏览器参数
  history.pushState({}, "", url);
  treeRef.value?.setCheckedKeys([data.id]);
};

// 添加页面
const handleAdd = (type: TabType, id?: string | number) => {
  propId.value = id;
  visible[type] = true;
};

// 关闭添加页面
const handleClose = (type: TabType, refresh: boolean) => {
  if (refresh) {
    switch (type) {
      case TabType.sales:
        saleRef.value?.onReload();
        break;
      case TabType.clearance:
        clearanceRef.value?.onReload();
        break;
      default:
        break;
    }
  }
  visible[type] = false;
};

onMounted(() => {
  getDailyNecessitiesTree(props.type, queueId.value).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      const generate = (list: TreeType[], parentId?: string | number) => {
        const arr: TreeType[] = [];
        list.forEach(item => {
          const payload: TreeType = {
            id: `${!!parentId ? parentId + "-" : ""}${item.value}`,
            value: item.value,
            label: item.label
          };
          if (!!item.childs?.length) {
            payload.childs = generate(item.childs, item.value);
          }
          arr.push(payload);
        });
        return arr;
      };
      treeState.data = [{ id: "all", value: "all", label: proxy!.$t("merak.all") }, ...generate(data)];
      if (!!route.query.key) {
        const routeKeys = route.query.key.toString().split("-");
        treeState.value = routeKeys[routeKeys.length - 1];
        treeRef.value?.setCheckedKeys([route.query.key.toString()]);
      } else {
        treeState.value = "all";
        treeRef.value?.setCheckedKeys(["all"]);
      }
    }
  });
});
</script>

<style scoped lang="scss">
.merak-container-has-aside {
  position: relative;
}

.merak-aside {
  display: flex;
  flex-direction: column;
  & > :not(:first-child) {
    margin-top: var(--merak-space);
  }
  & > .tree-wrapper {
    flex: 1;
    min-height: 0;
  }
  .title {
    font-size: 16px;
  }
}
.el-tree {
  :deep(.el-tree-node.is-checked .el-tree-node__content:has(.is-leaf)) {
    color: #fff !important;
    background-color: var(--el-color-primary) !important;
  }
}

.el-tabs {
  display: flex;
  flex-direction: column;
  margin-top: calc(0px - var(--merak-space));
  height: calc(100% + var(--merak-space));
  :deep(.el-tabs__nav-wrap::after) {
    height: 1px;
  }
  :deep(.el-tabs__content) {
    position: relative;
    flex: 1;
    min-height: 0;
    overflow: hidden;
    .el-tab-pane {
      position: absolute;
      display: block !important;
      width: 100%;
      height: 100%;
      overflow: hidden;
      & > div {
        height: 100%;
      }
    }
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
